package com.cradom.event.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.cradom.event.model.Event;
import com.cradom.event.service.EventService;
import com.cradom.event.utils.Config;
import com.cradom.event.utils.JsonUtil;

@Controller
public class IndexController {

	@Resource
	private EventService eventService;
	
	/**
	 * 获取全部事件，显示到首页表格中
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String getEventFirstPage(HttpServletRequest request){
		Integer pageNum = 1;
		PageHelper.startPage(pageNum,Config.PAGESIZE);
		List<Event> eventList=eventService.getEvent();
			
		Page<Event> listEvent=(Page<Event>)eventList;
		request.setAttribute("total", listEvent.getPages()); //总页数
		request.setAttribute("eventList", listEvent); //已分页的内容
		return "forward:/index.jsp";
		
	}
	
	@RequestMapping("/getEvent")
	public void getEvent(HttpServletRequest request,@RequestParam(value="pageNum")Integer pageNum,HttpServletResponse response) throws IOException{
		PageHelper.startPage(pageNum,Config.PAGESIZE);
		List<Event> eventList=eventService.getEvent();
			
		Page<Event> listEvent=(Page<Event>)eventList;
		request.setCharacterEncoding("utf-8");  //这里不设置编码会有乱码
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache"); 
        PrintWriter out = response.getWriter();  //输出中文，这一句一定要放到后面，否则中文返回到页面是乱码  
        JsonUtil<Page<Event>> json=new JsonUtil<Page<Event>>();
        out.print(json.objectToJson(listEvent));
	}
}
